package com.food.controller;

import com.food.common.Result;
import com.food.model.UserProfile;
import com.food.model.UserGoal;
import com.food.service.UserService;
import com.food.service.FileService;
import com.food.mapper.UserMapper;
import com.food.dto.UserRegisterDTO;
import com.food.dto.UserLoginDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.MediaType;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.beans.factory.annotation.Value;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.core.io.DefaultResourceLoader;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/api/user")
public class UserController {
    
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private FileService fileService;
    
    @Autowired
    private UserMapper userMapper;

    @Value("${app.base-url}")
    private String baseUrl;

    @Value("${spring.web.resources.static-locations:classpath:/static/}")
    private String staticPath;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public Result<?> register(@Valid @RequestBody UserRegisterDTO registerDTO) {
        try {
            // 基本验证
            if (registerDTO.getUsername() == null || registerDTO.getUsername().trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }
            if (registerDTO.getPassword() == null || registerDTO.getPassword().trim().isEmpty()) {
                return Result.error("密码不能为空");
            }
            if (registerDTO.getEmail() == null || registerDTO.getEmail().trim().isEmpty()) {
                return Result.error("邮箱不能为空");
            }

            return userService.register(registerDTO);
        } catch (Exception e) {
            return Result.error("注册失败：" + e.getMessage());
        }
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<?> login(@RequestBody UserLoginDTO loginDTO) {
        return userService.login(loginDTO);
    }

    @GetMapping("/profile")
    public Result<?> getProfile(@RequestParam Integer userId) {
        return userService.getProfile(userId);
    }

    @PutMapping("/profile")
    public Result<?> updateProfile(@RequestBody UserProfile profile) {
        return userService.updateProfile(profile);
    }

    @PutMapping("/password")
    public Result<?> updatePassword(
            @RequestParam Integer userId,
            @RequestParam String oldPassword,
            @RequestParam String newPassword) {
        return userService.updatePassword(userId, oldPassword, newPassword);
    }

    @ApiOperation("更新用户头像")
    @PostMapping(value = "/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<?> updateAvatar(
            @RequestParam Integer userId,
            @ApiParam(value = "头像文件", required = true)
            @RequestPart("file") MultipartFile file) {
        try {
            if (userMapper.findById(userId) == null) {
                return Result.error("用户不存在");
            }
            
            String avatarUrl = fileService.uploadFile(file);
            userMapper.updateAvatar(userId, avatarUrl);
            logger.info("Updated avatar for userId {} to {}", userId, avatarUrl);
            return Result.success(avatarUrl);
        } catch (IllegalArgumentException e) {
            logger.warn("Invalid file upload attempt: {}", e.getMessage());
            return Result.error(e.getMessage());
        } catch (IOException e) {
            logger.error("Error uploading avatar for userId {}: {}", userId, e.getMessage());
            return Result.error("上传失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "获取用户头像", notes = "根据用户ID获取头像URL")
    @GetMapping("/avatar")
    public Result<?> getUserAvatar(
        @ApiParam(value = "用户ID", required = true, type = "integer")
        @RequestParam Integer userId) {
        try {
            logger.debug("Getting avatar for userId: {}", userId);
            
            String avatarUrl = userMapper.getAvatarUrl(userId);
            logger.debug("Database avatar URL for userId {}: {}", userId, avatarUrl);
            
            if (userMapper.findById(userId) == null) {
                logger.warn("User not found for userId: {}", userId);
                return Result.error("用户不存在");
            }
            
            if (avatarUrl == null || avatarUrl.isEmpty()) {
                logger.debug("No avatar found for userId {}, using default", userId);
                return Result.success(baseUrl + "/static/images/avatar/default.jpg");
            }
            
            return Result.success(avatarUrl);
        } catch (Exception e) {
            logger.error("Error getting avatar for userId {}: {}", userId, e.getMessage());
            return Result.success(baseUrl + "/static/images/avatar/default.jpg");
        }
    }

    @PostMapping("/avatar/preset")
    public Result<?> updateAvatarByPreset(
            @RequestParam Integer userId,
            @RequestParam String avatarName) {
        try {
            if (!avatarName.toLowerCase().endsWith(".jpg") && !avatarName.toLowerCase().endsWith(".png")) {
                avatarName = avatarName + ".jpg";
            }
            
            String avatarUrl = baseUrl + "/static/images/avatar/" + avatarName;
            userMapper.updateAvatar(userId, avatarUrl);
            logger.info("Updated avatar for userId {} to {}", userId, avatarUrl);
            return Result.success(avatarUrl);
        } catch (Exception e) {
            logger.error("Error updating preset avatar for userId {}: {}", userId, e.getMessage());
            return Result.error("更新头像失败：" + e.getMessage());
        }
    }

    @GetMapping("/avatar/presets")
    public Result<?> getPresetAvatars() {
        try {
            List<String> avatarUrls = Arrays.asList(
                baseUrl + "/static/images/avatar/avatar1.jpg",
                baseUrl + "/static/images/avatar/avatar2.jpg",
                baseUrl + "/static/images/avatar/avatar3.jpg",
                baseUrl + "/static/images/avatar/default.jpg"
            );
            return Result.success(avatarUrls);
        } catch (Exception e) {
            logger.error("Error getting preset avatars", e);
            return Result.error("获取预设头像失败：" + e.getMessage());
        }
    }

    @GetMapping("/test-avatar")
    public ResponseEntity<Resource> testAvatar() {
        try {
            Resource resource = new ClassPathResource("static/images/avatar/default.jpg");
            return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_JPEG)
                    .body(resource);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }
    }
} 